package com.ruoyi.sxt.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;

import com.ruoyi.common.core.domain.entity.SxtBumen;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;

import com.ruoyi.sxt.mapper.SxtBumenMapper;
import com.ruoyi.sxt.service.ISxtBumenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 部门Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-15
 */
@Service
public class SxtBumenServiceImpl implements ISxtBumenService
{
    @Autowired
    private SxtBumenMapper sxtBumenMapper;

    /**
     * 查询部门
     * 
     * @param deptId 部门主键
     * @return 部门
     */
    @Override
    public SxtBumen selectSxtBumenByDeptId(Long deptId)
    {
        return sxtBumenMapper.selectSxtBumenByDeptId(deptId);
    }

    /**
     * 查询部门列表
     * 
     * @param sxtBumen 部门
     * @return 部门
     */
    @Override
    public List<SxtBumen> selectSxtBumenList(SxtBumen sxtBumen)
    {
        return sxtBumenMapper.selectSxtBumenList(sxtBumen);
    }

    /**
     * 新增部门
     * 
     * @param sxtBumen 部门
     * @return 结果
     */
    @Override
    public int insertSxtBumen(SxtBumen sxtBumen)
    {
        sxtBumen.setCreateTime(DateUtils.getNowDate());
        SxtBumen info = sxtBumenMapper.selectSxtBumenByDeptId(sxtBumen.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        sxtBumen.setAncestors(info.getAncestors() + "," + sxtBumen.getParentId());
        return sxtBumenMapper.insertSxtBumen(sxtBumen);
    }

    /**
     * 修改部门
     * 
     * @param sxtBumen 部门
     * @return 结果
     */
    @Override
    public int updateSxtBumen(SxtBumen sxtBumen)
    {
        sxtBumen.setUpdateTime(DateUtils.getNowDate());
        SxtBumen newParentBumen = sxtBumenMapper.selectSxtBumenByDeptId(sxtBumen.getParentId());
        SxtBumen oldBumen = sxtBumenMapper.selectSxtBumenByDeptId(sxtBumen.getDeptId());
        if (StringUtils.isNotNull(newParentBumen) && StringUtils.isNotNull(oldBumen))
        {
            String newAncestors = newParentBumen.getAncestors() + "," + newParentBumen.getDeptId();
            String oldAncestors = oldBumen.getAncestors();
            sxtBumen.setAncestors(newAncestors);
            updateDeptChildren(sxtBumen.getDeptId(), newAncestors, oldAncestors);
        }
        int result = sxtBumenMapper.updateSxtBumen(sxtBumen);
        if (UserConstants.DEPT_NORMAL.equals(sxtBumen.getStatus()) && StringUtils.isNotEmpty(sxtBumen.getAncestors())
                && !StringUtils.equals("0", sxtBumen.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(sxtBumen);
        }
        return result;

    }

    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SxtBumen> children = sxtBumenMapper.selectChildrenDeptById(deptId);
        for (SxtBumen child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            sxtBumenMapper.updateDeptChildren(children);
        }
    }

    private void updateParentDeptStatusNormal(SxtBumen sxtBumen)
    {
        String ancestors = sxtBumen.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        sxtBumenMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 批量删除部门
     * 
     * @param deptIds 需要删除的部门主键
     * @return 结果
     */
    @Override
    public int deleteSxtBumenByDeptIds(Long[] deptIds)
    {
        return sxtBumenMapper.deleteSxtBumenByDeptIds(deptIds);
    }

    /**
     * 删除部门信息
     * 
     * @param deptId 部门主键
     * @return 结果
     */
    @Override
    public int deleteSxtBumenByDeptId(Long deptId)
    {
        return sxtBumenMapper.deleteSxtBumenByDeptId(deptId);
    }

    /**
     * 查询部门树结构信息
     *
     * @param bumen 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectBumenTreeList(SxtBumen bumen)
    {
        List<SxtBumen> bumens = selectSxtBumenList(bumen);
        return buildBumenTreeSelect(bumens);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param bumens 部门列表
     * @return 下拉树结构列表
     */

    public List<TreeSelect> buildBumenTreeSelect(List<SxtBumen> bumens)
    {
        List<SxtBumen> bumenTrees = buildBumenTree(bumens);
        return bumenTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param bumens 部门列表
     * @return 树结构列表
     */

    public List<SxtBumen> buildBumenTree(List<SxtBumen> bumens)
    {
        List<SxtBumen> returnList = new ArrayList<SxtBumen>();
        List<Long> tempList = bumens.stream().map(SxtBumen::getDeptId).collect(Collectors.toList());
        for (SxtBumen bumen : bumens)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(bumen.getParentId()))
            {
                recursionFn(bumens, bumen);
                returnList.add(bumen);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = bumens;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SxtBumen> list, SxtBumen t)
    {
        // 得到子节点列表
        List<SxtBumen> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SxtBumen tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SxtBumen> getChildList(List<SxtBumen> list, SxtBumen t)
    {
        List<SxtBumen> tlist = new ArrayList<SxtBumen>();
        Iterator<SxtBumen> it = list.iterator();
        while (it.hasNext())
        {
            SxtBumen n = (SxtBumen) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SxtBumen> list, SxtBumen t)
    {
        return getChildList(list, t).size() > 0;
    }
}
